//
//  KAWebVC.swift
//  kano
//
//  Created by Sophia on 2024/8/14.
//

import WebKit

class KAWebVC: KABaseVC  {

    lazy var var_webView: WKWebView = {

        let var_config = WKWebViewConfiguration()
        let var_uerContentVC = WKUserContentController()
        var_config.userContentController = var_uerContentVC;

        let var_webView = WKWebView(frame: CGRectMake(0, UIDevice.ka_fullNavHeight, var_screenWidth, UIDevice.ka_viewHeight), configuration: var_config)
        var_webView.uiDelegate = self
        var_webView.navigationDelegate = self
        var_webView.allowsBackForwardNavigationGestures = true
        return var_webView
    }()
    
    lazy var var_progressView: UIProgressView = {
        let var_progressView = UIProgressView(frame: CGRectMake(0, UIDevice.ka_fullNavHeight+1, view.width, 2))
        var_progressView.tintColor = .themeColor
        var_progressView.trackTintColor = .clear
        return var_progressView
    }()
    var var_title: String
    var var_url: URL
    
    //MARK: - init
    init(title: String, url: URL) {
        var_title = title
        var_url = url
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .color66748A
        
        ka_showCustomerNavBar(type: .center)
        var_navBar.var_titleLabel.text = var_title
        var_navBar.ka_gobackBlock({ [weak self] in
            self?.navigationController?.popToRootViewController(animated: true)
        })
        var_prohibitReturn = true
        
        ka_setUI()
    }
    
    func ka_setUI() {
        view.addSubview(var_webView)
        view.addSubview(var_progressView)
        var_webView.scrollView.delegate = self
        
        if #available(iOS 11.0, *) {
            var_webView.scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            automaticallyAdjustsScrollViewInsets = false
        }

        var var_encoding : UInt = 0
        var_webView.addObserver(self, forKeyPath: "estimatedProgress", context: &var_encoding)
        
        ka_startRequest()
    }
    
    func ka_startRequest() {
        print("web url = \(self.var_url)")

        if var_url.isFileURL {
            var_webView.loadFileURL(var_url, allowingReadAccessTo: var_url)
        } else {
            var var_request = URLRequest(url: var_url)
            var_request.cachePolicy = .reloadIgnoringCacheData
            var_webView.load(var_request as URLRequest)
        }
    }
    
    //kvo
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("Progress = \(var_webView.estimatedProgress)")
        if keyPath == "estimatedProgress" {
            var_progressView.progress = Float(var_webView.estimatedProgress)
            if var_webView.estimatedProgress >= 1.0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: DispatchWorkItem(block: { [self] in
                    var_progressView.progress = 0
                }))
            }
        } else{
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}

//MARK: - UIScrollViewDelegate
extension KAWebVC: UIScrollViewDelegate {
    
}

//MARK: - WKNavigationDelegate
extension KAWebVC: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        var_progressView.setProgress(0.0, animated: false)
    }
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        var_progressView.setProgress(0.0, animated: false)
    }
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        //let var_urlStr = navigationResponse.response.url?.absoluteString
        decisionHandler(.allow);
    }

    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        
    }
}

//MARK: - WKUIDelegate
extension KAWebVC: WKUIDelegate {
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    
    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let var_alertVC = UIAlertController(title: "", message: message, preferredStyle: .alert)
        var_alertVC.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
            completionHandler(false)
        }))
        var_alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
            completionHandler(true)
        }))
        self.present(var_alertVC, animated: true)
    }

    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let var_alertVC = UIAlertController(title: prompt, message: "", preferredStyle: .alert)
        var_alertVC.addTextField { textField in
            textField.text = defaultText
        }
        var_alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
            completionHandler(var_alertVC.textFields![0].text ?? "");
        }))
        self.present(var_alertVC, animated: true)
    }
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if (!navigationAction.targetFrame!.isMainFrame) {
            webView.load(navigationAction.request)
        }
        return nil;
    }
}

//MARK: - WKScriptMessageHandler
extension KAWebVC: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
    

}

